﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using Pfz.DataTypes;
using Pfz.Factoring;

namespace Pfz.WpfControls.ValueControls
{
	/// <summary>
	/// Controls for editing DateTime values.
	/// </summary>
	[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
	[AutoRegisterInControlFactory(typeof(DateTime))]
	[AutoRegisterInControlFactory(typeof(DateTime?))]
	internal sealed class DateTimeControl:
		UserControl,
		IValueControl
	{
		private ValueControl<Date?> _dateControl = new ValueControl<Date?>();
		private ValueControl<Time?> _timeControl = new ValueControl<Time?>();
		
		/// <summary>
		/// Creates a new DateTime control.
		/// </summary>
		public DateTimeControl()
		{
			var panel = new StackPanel();
			panel.Orientation = Orientation.Horizontal;
			
			var panelChildren = panel.Children;
			panelChildren.Add(_dateControl);
			panelChildren.Add(new Label { Content = " - "});
			panelChildren.Add(_timeControl);
			
			Content = panel;
		}
	
		/// <summary>
		///  Clears the Date and Time.
		/// </summary>
		public void Clear()
		{
			_dateControl.Clear();
			_timeControl.Clear();
		}

		/// <summary>
		/// Gets or sets a value indicating that this control is read-only.
		/// </summary>
		public bool IsReadOnly
		{
			get
			{
				return _dateControl.IsReadOnly;
			}
			set
			{
				_dateControl.IsReadOnly = value;
				_timeControl.IsReadOnly = value;
			}
		}

		/// <summary>
		/// Gets the value of this control.
		/// </summary>
		public DateTime? Value
		{
			get
			{
				var date = _dateControl.Value;
				if (!date.HasValue)
					return null;
				
				return date.Value + _timeControl.Value.Value; 
			}
			set
			{
				if (value == null || value.Value == default(DateTime))
				{
					Clear();
					return;
				}
				
				_dateControl.Value = (Date)value;
				_timeControl.Value = (Time)value;
			}
		}

		#region IValueContainer Members
			object IValueContainer.Value
			{
				get
				{
					return Value;
				}
				set
				{
					Value = (DateTime?)value;
				}
			}
		#endregion
	}
}
